var util = require('../../utils/util.js');
var api = require('../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openid: "",
    body: "",
    userOrderId: "",
    price: "",
    topic_name:"",
    isDisabled:false, //是否可以点击支付按钮
    countDownDay: "00",
    countDownHour: "00",
    countDownMinute: "00",
    countDownSecond: "00",
  },
  pay: function() {
    //校验openid userOrderId 
    if (this.data.openid == "" || this.data.userOrderId == "") {
      wx.showModal({
        title: '提示',
        content: '付款失败缺少必要数据',
        showCancel: false
      })
      return false
    }

    this.requestPayParam(this.data.openid, this.data.body, this.data.userOrderId);
  },
  //向服务请求支付参数
  requestPayParam(openid, body, userOrderId) {
    let that = this;
    util.request(api.WechatPayOrder, {
      openid: openid,
      body: that.data.topic_name,
      userOrderId: userOrderId
    }, 'POST', false).then(function(res) {
      if (res.code === 200) {
        let payParam = res.result;
        that.setData({
          isDisabled:true
        })
        wx.requestPayment({
          'timeStamp': payParam.timeStamp,
          'nonceStr': payParam.nonceStr,
          'package': "prepay_id=" + payParam.prepay_id,
          'signType': "MD5",
          'paySign': payParam.sign,
          'success': function(res) {
            // wx.showToast({
            //   title: '去个人中心->我约的导师->待接收中查看订单',
            //   icon: 'none'
            // });
            wx.navigateTo({
              url: '../../myPages/paymentSuccess/paymentSuccess?price=' + that.data.price,
            })
            // wx.reLaunch({
            //   url: '../../myPages/paymentSuccess/paymentSuccess?price=' + that.data.price,
            // })
            // wx.showModal({
            //   content: '付款成功：去个人中心->我约的导师->待接受中查看订单，点击确定返回首页',
            //   complete: res => {
            //     wx.switchTab({
            //       url: '/pages/index/index',
            //     });
            //   },
            //   showCancel: false
            // })
          },
          'fail': function(res) {
            wx.showToast({
              title: '付款失败：res',
              icon: 'none'
            });
          }
        })
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        });
      }
    });
  },
  getUserOrderTimeByIdStatus: function(userOrderId, status) {
    let that = this
    util.request(api.GetUserOrderTimeByIdStatus, {
      userOrderId: userOrderId, //订单id
      status: status //订单状态
    }, 'GET').then(function(res) {
      if (res.code == 200 || res.result.createTime != undefined) {
        //取剩余30分钟
        // console.log(res.result.createTime)
        var format = res.result.createTime.replace(/-/g, '/')
        // console.log(format)
        var oldTime = new Date(format);  
        oldTime.setMinutes(oldTime.getMinutes() + 30); 
        var newTime = oldTime.getTime();  
        that.count_down(newTime);
      } else {
        wx.showToast({
          title: '剩余时间加载失败',
          icon: 'none'
        });
      }
    })
  },
  count_down: function (newTime) {
    console.log()
    // var totalSecond = Date.parse(new Date(newTime)) / 1000 - Date.parse(new Date()) / 1000;
    var totalSecond = newTime / 1000 - Date.parse(new Date()) / 1000;
    // console.log(totalSecond)
    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        wx.showToast({
          title: '订单已经失效',
          icon:"none"
        });
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          isDisabled:true
        });
      }
    }.bind(this), 1000);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let openid = wx.getStorageSync('userInfo').openid;
    let body = options.body;
    let userOrderId = options.userOrderId;
    let price = options.price
    let topic_name = options.topic_name
    this.setData({
      openid: openid,
      body: body,
      userOrderId: userOrderId,
      price: price,
      topic_name: topic_name
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    //加载订单剩余时间 代付款状态为1
    this.getUserOrderTimeByIdStatus(this.data.userOrderId, '1');
    wx.hideShareMenu();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})